import { Router } from 'vue-router'
import { useTabStore } from '../../store/tab'
import { useAppStore } from '../../store/app'
import { getMicroAppName, isMicroAppPath, getMicroAppTabSuffix } from '../../utils/microAppHelper'
import { normalizePath } from '../../utils/pathHelper'
import { setActivePath, setPathTitle, getPathTitle } from '../../utils/titleObserver'


// 不需要添加到标签页的路由
export const EXCLUDE_TAB = ['/login', '/404', '/403']

// 全局变量，用于记录上一次活动的标签路径
let lastActiveTabPath = '';

export function createTabGuard(router: Router) {
  // 防抖定时器
  let debounceTimer: NodeJS.Timeout | null = null
  const DEBOUNCE_DELAY = 50 // 50ms 防抖延迟

  router.afterEach((to) => {
    // 排除不需要添加标签的路由
    if (EXCLUDE_TAB.includes(to.path)) return
    
    // 清除之前的定时器
    if (debounceTimer) {
      clearTimeout(debounceTimer)
    }
    
    // 规范化路径，确保唯一性
    const path = normalizePath(to.fullPath)
    
    // 立即更新活动路径，确保titleObserver能正确工作
    setActivePath(path)
    
    // 获取路由元数据中的标题，预先设置到路径标题映射
    const routeTitle = to.meta?.title as string || to.name as string || '未命名页面'
    
    // 如果是微应用路径，可能已经有子应用设置的标题，优先使用缓存标题
    const cachedTitle = getPathTitle(path)
    if (isMicroAppPath(to.path) && cachedTitle) {
      // 已有缓存标题，不做处理
    } else if (routeTitle) {
      // 没有缓存标题或非微应用路径，设置标题
      setPathTitle(path, routeTitle)
    }
    
    // 防抖处理：延迟执行tab操作
    debounceTimer = setTimeout(() => {
      const tabStore = useTabStore()
      const appStore = useAppStore()
      
      // 获取路由元数据
      const { name, meta } = to
      const title = meta?.title as string || name as string || '未命名页面'
      const icon = meta?.icon as string
      const keepAlive = meta?.keepAlive as boolean || false
      const menuId = meta?.menuId as string | number
      
      // 移除权限检查 - 任何权限都可以添加标签
      // if (permission && !permissionStore.hasPermission(permission)) {
      //   console.log(`[Tab Guard] 用户没有权限 ${permission}，不添加标签`)
      //   return
      // }
      
      // 记录标签路径变化
      const isNewTab = !tabStore.tabs.some(tab => normalizePath(tab.path) === path);
      const isTabPathChanged = path !== lastActiveTabPath;
      lastActiveTabPath = path;
      
      // 微应用处理
      if (isMicroAppPath(to.path)) {
        const microAppName = getMicroAppName(to.path)
        if (microAppName) {
          appStore.setCurrentMicroApp(microAppName)
          
          // 获取微应用标签后缀
          const suffix = getMicroAppTabSuffix(to.path)
          
          // 获取最新的缓存标题（可能在此期间已被子应用更新）
          const latestTitle = getPathTitle(path) || title
          
          // 为微应用标签添加特殊标记
          const microAppTab = {
            name: name as string,
            path,
            title: latestTitle,
            icon: icon || 'app',
            keepAlive,
            isMicroApp: true,
            microAppName,
            suffix
          }
          
          // 检查是否已存在相同路径的标签
          if (isNewTab) {
            tabStore.addTab(microAppTab)
          }
        }
      } else {
        // 普通标签
        const normalTab = {
          name: name as string,
          path,
          title,
          icon,
          keepAlive,
          menuId
        }
        
        // 检查是否已存在相同路径的标签
        if (isNewTab) {
          tabStore.addTab(normalTab)
        }
      }
      
      // 无论如何都要高亮当前标签
      tabStore.setActiveTab(path)
    }, DEBOUNCE_DELAY)
  })
  
  // 导出lastActiveTabPath，供其他模块使用
  return {
    getLastActiveTabPath: () => lastActiveTabPath
  }
} 